<template>
    <div class="table_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="calc(100vh - 396px)"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'ADD_LABEL_GROUP'" type="primary" @click="addEditTag"> 新建标签组类别 </el-button>
            </template>
        </ZwTable>
        <!--新增&编辑标签组类别-->
        <Dialog :app-dialog="appDialog">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto">
                <el-form-item prop="name" label="标签组类别名称：">
                    <el-input
                        v-model.trim="formData.name"
                        placeholder="请输入标签组类别名称"
                        show-word-limit
                        maxlength="15"
                        @change="changeGroup">
                    </el-input>
                </el-form-item>
            </el-form>
        </Dialog>
        <!--删除标签组类别-->
        <Dialog :app-dialog="delDialog">
            <div class="del-dialog">
                <el-icon color="#E6A23C" size="18px"><WarningFilled /></el-icon>
                <div class="del-list">
                    <div class="del-title">你确定要删除【{{ formData.name }}】类别吗？</div>
                    <div class="del-text">删除后，该类别下的标签分组将自动移入默认标签组类别下。</div>
                </div>
            </div>
        </Dialog>
    </div>
</template>
<script lang="tsx" setup>
import { ref, reactive, computed } from 'vue';
import { groupTypeList, updateGroup, delGroupTag } from '@/api/customerCenter';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';
import { deepCopy } from '@/utils/helper';
import { ElMessage } from 'element-plus';
const formRef = ref(null);
const tableRef = ref(null);
const isRepeat = ref(false); //标签组类别是否重复
const formData = reactive({
    id: '', //标签组类别id
    name: '' //标签组类别名称
});
// 自定义校验标签组类别
const validateName = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('标签组类别名称不能为空'));
    } else if (isRepeat.value) {
        callback(new Error('标签组类别名称不允许重复'));
    } else {
        callback();
    }
};
// 表单校验
const rules = reactive({ name: [{ required: true, validator: validateName, trigger: 'change' }] });
// 取消新建&编辑标签组类别
const cancelHandel = () => {
    appDialog.visible = false;
};
// 确定新建&编辑标签组类别
const submitHandel = () => {
    isRepeat.value = false;
    formRef.value.validate((valid: any) => {
        if (valid) {
            let params = {};
            if (formData.id) {
                params = formData;
            } else {
                params = {
                    name: formData.name
                };
            }
            updateGroup(params)
                .then(() => {
                    appDialog.visible = false;
                    ElMessage.success(`${formData.id ? '编辑' : '新建'}标签组类别成功`);
                    reloadTable();
                })
                .catch(e => {
                    if (e?.code == 1500) {
                        isRepeat.value = true;
                        formRef.value.validateField('name');
                    }
                });
        }
    });
};
// 新建&编辑标签组类别弹框配置
const appDialog = reactive({
    visible: false,
    width: '35rem',
    title: '',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
// 取消删除标签组类别
const cancelDel = () => {
    delDialog.visible = false;
};
// 确认删除标签组类别
const submitDel = () => {
    delGroupTag({ id: formData.id })
        .then(() => {
            delDialog.visible = false;
            ElMessage.success('删除成功');
            reloadTable();
        })
        .catch(() => {
            ElMessage.error('删除失败');
        });
};
// 删除标签组类别弹框配置
const delDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '400px',
    cancel: cancelDel,
    submit: submitDel,
    cancelText: '取消',
    submitText: '确定'
});
const defaultParams = reactive({
    keyword: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '标签组类别',
            name: 'keyword',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入标签组类别名称'
        }
    ];
});
const tableOption = [
    {
        prop: 'name',
        label: '标签组类别',
        render({ row }) {
            return (
                <span>
                    {row.name || '--'}
                    <el-tag size="small" style={'margin-left:8px'} vShow={row.list_type == 1}>
                        默认
                    </el-tag>
                </span>
            );
        }
    },
    {
        prop: 'tag_group_num',
        label: '关联标签组数量'
    },
    {
        prop: 'created_at',
        label: '创建时间',
        render({ row }) {
            return <span>{row.created_at || '--'}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 200,
        isOperate: true,
        option({ row }) {
            if (row.list_type == 0) {
                return [
                    {
                        name: '编辑',
                        authCode: 'GROUP_EDIT',
                        click: (row: any) => {
                            addEditTag(row);
                        }
                    },
                    {
                        name: '删除',
                        authCode: 'GROUP_DEL',
                        click: (row: any) => {
                            del(row);
                        }
                    }
                ];
            }
        }
    }
];
const fetchApi = () => {
    return groupTypeList;
};
const search = (data?: any) => {
    if (data.keyword) {
        data.keyword = data.keyword.trim();
    }
    state.searchParams = deepCopy(data);
};
const reset = (v?: any) => {
    state.searchParams = deepCopy(v);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 新建&编辑标签组类别
const addEditTag = (val?: any) => {
    appDialog.title = `${val.id ? '编辑' : '新建'}标签组类别`;
    formData.name = val.name || '';
    formData.id = val.id || '';
    appDialog.visible = true;
    isRepeat.value = false;
};
// 切换标签组类别的值
const changeGroup = () => {
    isRepeat.value = true;
    formRef.value.clearValidate('name');
};
// 删除标签组类别
const del = (val?: any) => {
    formData.name = val.name;
    formData.id = val.id;
    delDialog.visible = true;
};
</script>
<style scoped lang="scss">
.table_container {
    height: calc(100vh - 242px);
    display: flex;
    flex-direction: column;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.del-dialog {
    padding: 8px 0;
    display: flex;

    .del-list {
        padding-left: 8px;

        .del-title {
            font-size: 14px;
            font-weight: 600;
            color: #33302d;
            margin-bottom: 12px;
        }

        .del-text {
            font-size: 12px;
            font-weight: 400;
            color: #999;
        }
    }
}
</style>
